from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import get_db
from models import Role, User
from schemas import RoleCreate, RoleUpdate, RoleSchema, ResponseModel, PaginatedResponse
from api.deps import get_current_active_user, get_current_superuser

router = APIRouter()

@router.get("", response_model=ResponseModel[PaginatedResponse[RoleSchema]])
def get_roles(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="角色名称搜索"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取角色列表"""
    query = db.query(Role)
    
    if name:
        query = query.filter(Role.name.contains(name))
    
    # 计算总数
    total = query.count()
    
    # 分页
    roles = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=roles
        )
    )

@router.get("/{role_id}", response_model=ResponseModel[RoleSchema])
def get_role(
    role_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
) -> Any:
    """获取角色详情"""
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(
            status_code=404,
            detail="角色不存在"
        )
    
    return ResponseModel(data=role)

@router.post("", response_model=ResponseModel[RoleSchema])
def create_role(
    role_in: RoleCreate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """创建角色"""
    # 检查角色名是否已存在
    role = db.query(Role).filter(Role.name == role_in.name).first()
    if role:
        raise HTTPException(
            status_code=400,
            detail="角色名已存在"
        )
    
    # 预定义角色级别映射
    predefined_roles = {
        "超级管理员": 500,
        "任务管理员": 400,
        "飞手": 300,
        "观测员": 200,
        "审计员": 100
    }
    
    # 确定角色级别
    level = role_in.level
    if role_in.name in predefined_roles and (level is None or level == 0):
        level = predefined_roles[role_in.name]
    elif level is None:
        level = 0  # 默认为自定义角色
    
    # 创建新角色
    db_role = Role(
        name=role_in.name,
        description=role_in.description,
        level=level
    )
    
    # 添加权限
    if role_in.permission_ids:
        from models import Permission
        permissions = db.query(Permission).filter(Permission.id.in_(role_in.permission_ids)).all()
        db_role.permissions = permissions
    
    db.add(db_role)
    db.commit()
    db.refresh(db_role)
    
    return ResponseModel(data=db_role)

@router.put("/{role_id}", response_model=ResponseModel[RoleSchema])
def update_role(
    role_id: int,
    role_in: RoleUpdate,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """更新角色"""
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(
            status_code=404,
            detail="角色不存在"
        )
    
    # 检查角色名是否已存在（排除当前角色）
    if role_in.name and role_in.name != role.name:
        existing_role = db.query(Role).filter(Role.name == role_in.name).first()
        if existing_role:
            raise HTTPException(
                status_code=400,
                detail="角色名已存在"
            )
    
    # 预定义角色级别映射
    predefined_roles = {
        "超级管理员": 500,
        "任务管理员": 400,
        "飞手": 300,
        "观测员": 200,
        "审计员": 100
    }
    
    # 更新字段
    update_data = role_in.dict(exclude_unset=True)
    
    # 处理权限
    if "permission_ids" in update_data:
        permission_ids = update_data.pop("permission_ids")
        from models import Permission
        permissions = db.query(Permission).filter(Permission.id.in_(permission_ids)).all()
        role.permissions = permissions
    
    # 特殊处理角色级别
    if "name" in update_data or "level" in update_data:
        # 如果修改了角色名且是预定义角色名，自动设置对应级别
        if "name" in update_data and update_data["name"] in predefined_roles:
            update_data["level"] = predefined_roles[update_data["name"]]
    
    for field, value in update_data.items():
        setattr(role, field, value)
    
    db.commit()
    db.refresh(role)
    
    return ResponseModel(data=role)

@router.delete("/{role_id}", response_model=ResponseModel[dict])
def delete_role(
    role_id: int,
    current_user: User = Depends(get_current_superuser),
    db: Session = Depends(get_db)
) -> Any:
    """删除角色"""
    role = db.query(Role).filter(Role.id == role_id).first()
    if not role:
        raise HTTPException(
            status_code=404,
            detail="角色不存在"
        )
    
    # 检查是否有用户使用该角色
    if role.users:
        raise HTTPException(
            status_code=400,
            detail="该角色正在被使用，无法删除"
        )
    
    db.delete(role)
    db.commit()
    
    return ResponseModel(data={"message": "角色删除成功"})